package org.sao.security.demo.controller;

import java.util.ArrayList;
import java.util.List;

import javax.validation.Valid;

import org.sao.security.demo.dto.User;
import org.sao.security.demo.exception.ZyException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.annotation.JsonView;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.bytebuddy.implementation.bytecode.Throw;

@RestController
@RequestMapping("/user")
public class UserController {
	
	
	@GetMapping("/me")
	public Object getCurrentUser(Authentication authentication) {
		return authentication.getPrincipal();
	}
	
	@GetMapping("/{id:\\d+}")
	@JsonView(User.UserDetailView.class)
	public User getUserInfo(@ApiParam(value="用户id") @PathVariable String id){
	// throw new ZyException(id,"用户不存在");
		User user =new User();
		user.setId(id);
		user.setUsername("zy");
		return user;		
	}
	
	@GetMapping
	@JsonView(User.UserSimpleView.class)
	public List<User> getUser(){
		List<User> users = new ArrayList<>();
		users.add(new User());
		users.add(new User());
		users.add(new User());
		return users;
	}
	
	
	@GetMapping("null")
	public User getcc(User user){
		
	if(user.getPassword().equals("123")) return user;
	return user;
	
	}
	
	@PostMapping
	@ApiOperation(value="创建新用户")
	public User createUser(@Valid @RequestBody User user,BindingResult result){
		 if (result.hasErrors()){
	            List<ObjectError> errorList = result.getAllErrors();
	            for(ObjectError error : errorList){
	                System.out.println(error.getDefaultMessage());
	            }
	        }
		//System.out.println(user);
		user.setId("1");
		return user;
	}
	
	@PutMapping("/{id:\\d+}")
	public User updUser(@Valid @RequestBody User user){
		//System.out.println(user);
		user.setId("1");
		return user;
	}

}
